package com.flute.framework.search.result.xmlresult.multi;

import java.util.Map;

import com.flute.framework.search.result.xmlresult.ExXpathTemplate;
import com.flute.framework.search.result.xmlresult.Node;
import com.flute.framework.search.result.xmlresult.XmlParser;

public class SimpleChildXpathParser extends BaseKeyValueXpathParser {
	static final String CHILD_KEY = "child";
	static final String PARENT_KEY = "parent";
	static final String SPLIT_KEY = "split";

	@Override
	public boolean correspond(String xpath) {
		if (super.correspond(xpath)) {
			Map<String, String> keyMap = getMap(xpath);
			if (keyMap.containsKey(CHILD_KEY) && keyMap.containsKey(PARENT_KEY)) {
				return true;
			}
		}
		return false;
	}

	@Override
	public ExXpathTemplate build(String xpath) {
		Map<String, String> keyMap = getMap(xpath);
		String value = keyMap.get(CHILD_KEY);
		Node root = XmlParser.getInstance().getNode(
				new String[] { "//" + value }, null, new String[] { "$value" });
		String loop = root.toXmlString();
		ExXpathTemplate template = new ExXpathTemplate();
		template.setLoop(loop);
		template.setSplit(keyMap.get(SPLIT_KEY));
		return template;
	}

	@Override
	public String getBaseXpath(String xpath) {
		Map<String, String> hashmap = getMap(xpath);
		String parent = xpath.substring(0, xpath.lastIndexOf("/") + 1);
		return parent + hashmap.get(PARENT_KEY);
	}

	public static void main(String[] args) {
		SimpleChildXpathParser parser = new SimpleChildXpathParser();
		System.out.println(parser.getMap("//aaa/#[child=b parent=d e=f]"));
	}
}
